package com.itlong.cloud.controller.system;


import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.DTO.property.PropertyUserInfoGetPageDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyUserSaveDTO;
import com.itlong.cloud.POJO.PO.PropertyGroupPO;
import com.itlong.cloud.POJO.PO.PropertyRolePO;
import com.itlong.cloud.POJO.PO.PropertyUserGroupRolePO;
import com.itlong.cloud.POJO.PO.PropertyUserInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.PropertyUserInfoGetOneVO;
import com.itlong.cloud.POJO.VO.property.PropertyUserInfoGetUserPageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.property.IPropertyGroupServiceClient;
import com.itlong.cloud.user.property.IPropertyRoleServiceClient;
import com.itlong.cloud.user.property.IPropertyUserServiceClient;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      物业-系统-人员Controller
 * </desc>
 *
 * @createDate 2017/10/16
 */
@RestController
@RequestMapping("/system/user")
@RefreshScope
public class PropertyUserInfoController extends BaseController{

    @Autowired
    IPropertyUserServiceClient iPropertyUserServiceClient;

    //物业项目服务层暴露接口
    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;

    @Autowired
    IPropertyGroupServiceClient iPropertyGroupServiceClient;

    @Autowired
    IPropertyRoleServiceClient iPropertyRoleServiceClient;

    @Value("${" + PlatformConstants.PROPERTY_USER_TOKEN_KEY + "}")
    String userTokenKey;
    

    /**
     * <desc>
     *      用户分页列表
     * </desc>
     *
     * @param pageDTO   物业人员分页DTO
     * @return  MessageVO 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/10/16
     */
    @PostMapping(path = "getPage")
    @ResponseBody
    @AuthAccessRequired
    public Object getPage(PropertyUserInfoGetPageDTO pageDTO){
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            pageDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyUserInfoGetPageDTO.class, request);
            Page<PropertyUserInfoGetUserPageVO> page=iPropertyUserServiceClient.getPage(pageDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),page);
        }catch (Exception e){
            throw new DataAccessException("【物业_系统_用户getPage】获取分页列表失败",e);
        }
    }

    /**
     * <desc>
     *      查看用户详情
     * </desc>
     *
     * @param propertyUserInfoPO
     * @return  MessageVO 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/10/16
     */
    @PostMapping(path = "getUserInfo")
    @ResponseBody
    public Object getUserInfo(PropertyUserInfoPO propertyUserInfoPO){
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyUserInfoPO = HttpProtocolUtil.parseRequestParamToDTO(PropertyUserInfoPO.class, request);
            PropertyUserInfoGetOneVO vo=iPropertyUserServiceClient.getOneVO(propertyUserInfoPO);
           // String[] roleIds= StringHandlerUtil.splitString(vo.getRoleId());
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),vo);
        }catch (Exception e){
            throw new DataAccessException("【物业_系统_用户getUserInfo】查看用户详情失败",e);
        }
    }

    /**
     * <desc>
     *      添加用户
     * </desc>
     * @param   propertyUserSaveDTO  物业人员保存DTO
     * @return MessageVO 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/10/16
     */
    @PostMapping(path = "save")
    @ResponseBody
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.USER_PROPERTY_SAVEUSER_LOG_DESC)
    public Object save(PropertyUserSaveDTO propertyUserSaveDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyUserSaveDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyUserSaveDTO.class, request);
            if (propertyUserSaveDTO == null || StringUtils.isBlank(propertyUserSaveDTO.getUserGroupRoleJson())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            try {
                List<PropertyUserGroupRolePO> propertyUserGroupRolePOS = JSON.parseArray(propertyUserSaveDTO.getUserGroupRoleJson(), PropertyUserGroupRolePO.class);
                if (propertyUserGroupRolePOS == null || propertyUserGroupRolePOS.isEmpty()) {
                    return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
            } catch (Exception e) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            //物业账号不能重复
            String userName = propertyUserSaveDTO.getUserName();
            if (StringUtils.isBlank(userName)) {
                return new MessageVO(PropertyErrorCodeEnum.USER_USER_USERNAME_ILLEGAL.getErrorCode());
            }
            userName = userName.trim();
            propertyUserSaveDTO.setUserName(userName);
            /*if (!userName.matches("^[a-zA-Z][a-zA-Z0-9]{4,29}$")) {
                return new MessageVO(PropertyErrorCodeEnum.USER_USER_NAME_IS_ILLEGAL.getErrorCode());
            }*/
            Map<String, Object> params = new HashMap<>();
            params.put("userName", userName);
            boolean isExist = iPropertyUserServiceClient.isPropertyUserExist(params);
            if (isExist) {
                return new MessageVO(PropertyErrorCodeEnum.USER_USER_USERNAME_EXIST.getErrorCode());
            }

            //添加或更新物业人员前对部门和角色进行存在性校验
            MessageVO checkMessage = groupAndRoleCheck(propertyUserSaveDTO);
            if (checkMessage != null){
                return checkMessage;
            }

            iPropertyUserServiceClient.save(propertyUserSaveDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_用户save】添加用户失败", e);
        }
    }


    /**
     * <desc>
     *      添加或更新物业人员前，对部门和角色进行存在性校验
     * <desc/>
     * @param  propertyUserSaveDTO  保存人员DTO
     * @return MessageVO 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/12/27
     */
    private MessageVO groupAndRoleCheck(PropertyUserSaveDTO propertyUserSaveDTO) {
        String groupId = propertyUserSaveDTO.getGroupId();
        String roleId = propertyUserSaveDTO.getRoleId();
        /*if (StringUtils.isBlank(groupId) || StringUtils.isBlank(roleId)) {
            return new MessageVO(PropertyErrorCodeEnum.USER_USER_GROUPID_ROLEID_EXIST.getErrorCode());
        }*/

        //检查部门或角色是否禁用或不存在
        Map<String, Object> param = new HashMap<>();
        param.put("groupId", groupId);
        param.put("status", DataStatusEnum.NORMAL.getType());
        if (!StringUtils.isBlank(groupId)) {
            List<PropertyGroupPO> groupPOS = iPropertyGroupServiceClient.getByFeilds(param);
            if (groupPOS == null || groupPOS.isEmpty()) {
                return new MessageVO(PropertyErrorCodeEnum.USER_GROUPID_IS_BAN_OR_NOT_EXIST.getErrorCode());
            }
        }
        param.remove("groupId");
        param.put("roleId", roleId);
        param.put("mark", "noGroupId");
        if (!StringUtils.isBlank(roleId)) {

            List<PropertyRolePO> rolePOS = iPropertyRoleServiceClient.getByFields(param);
            if (rolePOS == null || rolePOS.isEmpty()) {
                return new MessageVO(PropertyErrorCodeEnum.USER_ROLEID_IS_BAN_OR_NOT_EXIST.getErrorCode());
            }
        }

        return null;
    }

    /**
     * <desc>
     *      更新用户
     * </desc>
     *
     * @param propertyUserSaveDTO    物业用户实体类
     * @return  MessageVO 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/10/16
     */
    @PostMapping(path = "update")
    @ResponseBody
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.USER_PROPERTY_UPDATEUSER_LOG_DESC)
    public Object update(PropertyUserSaveDTO propertyUserSaveDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyUserSaveDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyUserSaveDTO.class, request);
            if (propertyUserSaveDTO == null || StringUtils.isBlank(propertyUserSaveDTO.getUserGroupRoleJson())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            try {
                List<PropertyUserGroupRolePO> propertyUserGroupRolePOS = JSON.parseArray(propertyUserSaveDTO.getUserGroupRoleJson(), PropertyUserGroupRolePO.class);
                if (propertyUserGroupRolePOS == null || propertyUserGroupRolePOS.isEmpty()) {
                    return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
            } catch (Exception e) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            //物业账号不能重复
            if (StringUtils.isBlank(propertyUserSaveDTO.getUserName())) {
                return new MessageVO(PropertyErrorCodeEnum.USER_USER_USERNAME_ILLEGAL.getErrorCode());
            }
            Map<String, Object> params = new HashMap<>();
            params.put("userName", propertyUserSaveDTO.getUserName());
            params.put("userIdNot", propertyUserSaveDTO.getUserId());
            boolean propertyUserExist = iPropertyUserServiceClient.isPropertyUserExist(params);
            if (propertyUserExist) {
                return new MessageVO(PropertyErrorCodeEnum.USER_USER_USERNAME_EXIST.getErrorCode());
            }

            //添加或更新物业人员前对部门和角色进行存在性校验
            MessageVO checkMessage = groupAndRoleCheck(propertyUserSaveDTO);
            if (checkMessage != null){
                return checkMessage;
            }

            int result = iPropertyUserServiceClient.update(propertyUserSaveDTO);
            return new MessageVO(propertyUserSaveDTO.getUserId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_用户update】更新用户失败", e);
        }
    }

    /**
     * <desc>
     *      删除用户（批量）
     * </desc>
     * @param userIds   批量删除的userId
     * @return  MessageVO 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/10/16
     */
    @PostMapping(path = "delete")
    @ResponseBody
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.USER_PROPERTY_DELETEUSER_LOG_DESC)
    public Object delete(String userIds) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            userIds = request.getAttribute("userIds") == null ? null : request.getAttribute("userIds").toString();
            if(StringUtils.isEmpty(userIds)){
                return new MessageVO(PropertyErrorCodeEnum.USER_USER_USERID_NOT_NULL.getErrorCode());
            }
            iPropertyUserServiceClient.delete(userIds);
            return new MessageVO(userIds,BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_用户delete】删除用户失败", e);
        }
    }

    /**
     * <desc>
     *      根据字段参数灵活查询人员
     * </desc>
     * @param propertyUserInfoGetPageDTO   分页查询DTO
     * @return  MessageVO 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/10/16
     */
    @PostMapping(path = "getList")
    @ResponseBody
    @LoggerInfo(operateDesc = LogDescConstant.USER_PROPERTY_DELETEUSER_LOG_DESC)
    public Object getList(PropertyUserInfoGetPageDTO propertyUserInfoGetPageDTO) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        propertyUserInfoGetPageDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyUserInfoGetPageDTO.class, request);
        Map<String,Object> params = new HashMap<>();
        params.put("projectId",propertyUserInfoGetPageDTO.getProjectId());
        List<PropertyUserInfoPO> userList = iPropertyUserServiceClient.getList(params);
        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),userList);
    }


    /**
     * <desc>
     *      重置用户密码（批量）
     * </desc>
     *
     * @param userIds 用户id 多个,号分隔
     * @return   MessageVO 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/11/8
     */
    @ResponseBody
    @PostMapping(path = "resetPassword")
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.USER_PROPERTY_RESETPASSWORD_LOG_DESC)
    public Object resetPassword(String userIds){
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            userIds = request.getAttribute("userIds") == null ? null : request.getAttribute("userIds").toString();
            if(StringUtils.isEmpty(userIds)){
                return new MessageVO(PropertyErrorCodeEnum.USER_USER_USERID_NOT_NULL.getErrorCode());
            }
            iPropertyUserServiceClient.resetPassword(userIds);
            return new MessageVO(userIds,BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【物业_系统_用户resetPassword】重置用户密码异常", e);
        }
    }

    /**
     * <desc>
     *      修改密码
     * <desc/>
     * @param   loginUserId  待更新密码的用户userId
     * @param   oldPassword  老密码
     * @param   newPassword 新密码
     * @return      MessageVO 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/11/8
     */
    @ResponseBody
    @PostMapping(path = "updatePassword")
    @LoggerInfo(operateDesc = LogDescConstant.USER_PROPERTY_UPDATEPASSWORD_LOG_DESC)
    public Object updatePassword(String loginUserId,
                                    String oldPassword,
                                    String newPassword) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            loginUserId = request.getAttribute("loginUserId") == null ? null : request.getAttribute("loginUserId").toString();
            oldPassword = request.getAttribute("oldPassword") == null ? null : request.getAttribute("oldPassword").toString();
            newPassword = request.getAttribute("newPassword") == null ? null : request.getAttribute("newPassword").toString();
            if (StringUtils.isEmpty(loginUserId)) {
                return new MessageVO(PropertyErrorCodeEnum.USER_USER_USERID_NOT_NULL.getErrorCode());
            }
            if (StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(newPassword)) {
                return new MessageVO(PropertyErrorCodeEnum.USER_USER_PASSWORD_NOT_NULL.getErrorCode());
            }

            //解密密码
            newPassword = UserTokenUtil.getPassword(newPassword,userTokenKey);
            oldPassword = UserTokenUtil.getPassword(oldPassword,userTokenKey);

            if (newPassword != null && newPassword.equals("itlong@111")) {
                return new MessageVO(PropertyErrorCodeEnum.USER_PASSWORD_DEFAULT_ERR.getErrorCode());
            }
            Map<String, Object> params = new HashMap<>();
            params.put("userId", loginUserId);
            params.put("password", Md5EncryptUtil.md5(oldPassword));
            boolean propertyUserExist = iPropertyUserServiceClient.isPropertyUserExist(params);
            if (!propertyUserExist) {
                return new MessageVO(PropertyErrorCodeEnum.USER_USER_PASSWORD_ERROR.getErrorCode());
            }
            if (oldPassword.equals(newPassword)) {
                return new MessageVO(PropertyErrorCodeEnum.USER_USER_PASSWORD_SAME.getErrorCode());
            }
            PropertyUserInfoPO userInfoPO = new PropertyUserInfoPO(loginUserId, null, Md5EncryptUtil.md5(newPassword));
            userInfoPO.setPasswordTime(new Date());
            iPropertyUserServiceClient.updateUser(userInfoPO);

            return new MessageVO(loginUserId,BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_用户updatePassword】更新用户密码异常", e);
        }
    }
}
